﻿#region References

using System.Linq;
using System.Collections.Generic;
using System.Windows.Input;
using Dev_house_Project.GUI.WPF.DataService;

#endregion

namespace Dev_house_Project.GUI.WPF.ViewModel
{
    public class MainViewModel:ViewModelBase
    {
        #region Fields
        
        private readonly DataServiceClient _dataClient;
        private DataStorageTypeEnum _dataStorageType;
        private List<Company> _companiesList;

        private DelegateCommand _saveData;

        #endregion

        #region Constructor

        public MainViewModel(DataStorageTypeEnum dataStorageType)
        {
            _dataClient = new DataServiceClient();

            _companiesList = new List<Company>();

            DataStorageType = dataStorageType;
        }       

        public MainViewModel():this(DataStorageTypeEnum.RemoteStorage){ }

        #endregion

        #region Properties

        public List<Company> Companies
        {
            get
            {
                return _companiesList;
            }
            private set
            {
                _companiesList = value;
                OnPropertyChanged("Companies");
            }
        }

        public DataStorageTypeEnum DataStorageType
        {
            get
            {
                return _dataStorageType;
            }
            set
            {
                _dataStorageType = value;
                _dataClient.Synchronize();
                
                if (_dataStorageType == DataStorageTypeEnum.LocalStorage)
                {
                    Companies = _dataClient.GetDataFromLocalStorage().ToList();
                }
                else
                {
                   Companies =  _dataClient.GetDataFromRemoteStorage().ToList();
                }

                OnPropertyChanged("DataStorageType");
            }
        }

        #endregion

        #region Commands

        public ICommand SaveDataCommand
        {
            get
            {
                if (null == _saveData)
                {
                    _saveData = new DelegateCommand(SaveData);
                }
                return _saveData;
            }
        }

        #endregion

        #region Methods

        void SaveData()
        {
            if (DataStorageType ==  DataStorageTypeEnum.LocalStorage)
            {
                _dataClient.SubmitChangesToLocalStorage(Companies.ToArray());
            }
            else
            {
                _dataClient.SubmitChangesToRemoteStorage(Companies.ToArray());
            }
        }

        #endregion
    }

    public enum DataStorageTypeEnum
    {
        LocalStorage,
        RemoteStorage
    }
}